﻿using SetSailModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SetSailCommon;
using SetSailControl;
using SetSailDal;

namespace SetSailView
{
    /// <summary>
    /// 联运存档
    /// </summary>
    public partial class Frm_LYCD : UserControl
    {
        public Frm_LYCD()
        {
            InitializeComponent();
        }

        //我的文档欧卡车队联运存档
        string MyFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\Euro Truck Simulator 2\\profiles\\";
        string PathFileName = "";//获取存档文件名
        string SelectCDLX = "";

        private void Frm_LYCD_Load(object sender, EventArgs e)
        {
            //默认全套档
            PathFileName = CookieData.getInstance().ZDGL.Where(a => a.MXDM == "QTFILE").FirstOrDefault().MXZ;

            //存档类型数据源
            List<Cookie_ZD> ls = CookieData.getInstance().ZDGL.Where(a => a.ZDDM == "CDDLX").ToList();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (var item in ls)
            {
                dic.Add(item.MXZ, item.MXMC);
            }
            TxtCDLX.DataSource = dic;
            TxtCDLX.SelectItem = new List<string>() { "全套" };
            SelectCDLX = "全套";

            //默认当前日期
            TxtCurrtDate.CurrentTime = DateTime.Today;

            //公告类型
            List<KeyValuePair<string, string>> lscbm_gglx = new List<KeyValuePair<string, string>>();
            lscbm_gglx.Add(new KeyValuePair<string, string>("联运", "联运公告"));
            lscbm_gglx.Add(new KeyValuePair<string, string>("提醒", "提醒公告"));
            TxtGGLX.Source = lscbm_gglx;
            TxtGGLX.SelectedValue = "联运";
        }

        /// <summary>
        /// 存档类型change事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtCDLX_SelectedItemChanged(object sender, EventArgs e)
        {
            if (TxtCDLX.SelectItem.Count == 0)
            {
                if (SelectCDLX == "全套")
                    TxtCDLX.SelectItem = new List<string>() { "本体" };
                else
                    TxtCDLX.SelectItem = new List<string>() { "全套" };
            }
            else
                SelectCDLX = TxtCDLX.SelectItem[0].Trim();
        }

        /// <summary>
        /// 获取IP
        /// </summary>
        private void ucBtnExt2_BtnClick(object sender, EventArgs e)
        {
            bool flag = CommonHelper.GetPing();
            if (flag)
            {
                TxtGetIP.InputText = "43.***.***.99";
            }
            else
            {
                MessShow.ShowHint("无法链接到服务器");
            }
        }

        /// <summary>
        /// 压缩存档
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucBtnExt3_BtnClick(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TxtGetIP.InputText.Trim()))
            {
                MessShow.ShowHint("请先获取服务器");
                return;
            }

            if (!Directory.Exists(MyFilePath))
            {
                MessShow.ShowHint("未查找到车队存档");
                return;
            }
            try
            {


                if (TxtCDLX.SelectItem[0].Trim() == "全套")
                    PathFileName = CookieData.getInstance().ZDGL.Where(a => a.MXDM == "QTFILE").FirstOrDefault().MXZ;
                else
                    PathFileName = CookieData.getInstance().ZDGL.Where(a => a.MXDM == "BTFILE").FirstOrDefault().MXZ;
                //路径
                TxtFilePath.InputText = MyFilePath + PathFileName + ".zip";
                CommonHelper.CreateZip(MyFilePath + PathFileName, TxtFilePath.InputText, MyFilePath);

                DataTable dt = new DataTable();
                dt.Columns.Add("Name", typeof(string));
                dt.Columns.Add("Type", typeof(string));
                dt.Columns.Add("UpdDate", typeof(string));
                dt.Columns.Add("Size", typeof(string));

                string[] arr = Directory.GetFiles(MyFilePath + PathFileName);

                foreach (var item in arr)
                {
                    FileInfo fi = new FileInfo(item);
                    DataRow row = dt.NewRow();
                    row["Name"] = fi.Name.Substring(0, fi.Name.LastIndexOf('.'));
                    row["Type"] = fi.Extension.Replace(".", "");
                    row["UpdDate"] = fi.LastAccessTime;
                    row["Size"] = Convert.ToInt32(fi.Length / 1024) + "KB";
                    dt.Rows.Add(row);
                }
                dataGridView1.DataSource = dt;
                MessShow.ShowSure("已压缩存档，请上传到云端");
            }
            catch (Exception ex)
            {
                MessShow.ShowMistake(ex.Message);
            }
        }

        /// <summary>
        /// 上传存档
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucBtnExt4_BtnClick(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TxtFilePath.InputText) || !File.Exists(TxtFilePath.InputText))
            {
                MessShow.ShowHint("请先设置存档");
                return;
            }
            if (TxtCDLX.SelectItem[0].Trim() == "全套")
                PathFileName = CookieData.getInstance().ZDGL.Where(a => a.MXDM == "QTFILE").FirstOrDefault().MXZ;
            else
                PathFileName = CookieData.getInstance().ZDGL.Where(a => a.MXDM == "BTFILE").FirstOrDefault().MXZ;
            try
            {
                string cosPath = TxtCurrtDate.CurrentTime.ToString("yyyy-MM-dd") + "/" + PathFileName + ".zip";
                ControlHelper.ThreadRunExt(this, () =>
                {
                    CosHelper helper = new CosHelper();
                    helper.PutObjectStream(cosPath, TxtFilePath.InputText);

                    ControlHelper.ThreadInvokerControl(this, () =>
                    {
                        if (helper.result2 != "ok")
                        {
                            MessShow.ShowHint(helper.result2);
                        }
                        else
                        {
                            //获取压缩包大小
                            decimal size = 0;
                            string[] arr = Directory.GetFiles(MyFilePath);
                            foreach (var item in arr)
                            {
                                if (item.Contains(PathFileName + ".zip"))
                                {
                                    FileInfo fi = new FileInfo(item);
                                    size = Convert.ToDecimal(Convert.ToDecimal(fi.Length) / 1024 / 1024);
                                    break;
                                }
                            }

                            QH_CDDJL cddjl = new QH_CDDJL();
                            cddjl.ID = CommonHelper.GetNewGuid();
                            cddjl.CZZH = CookieData.getInstance().YHXX.DLZH;
                            cddjl.SYLL = size;
                            cddjl.CDDLX = "存档";
                            cddjl.BZ = TxtCDLX.SelectItem[0].Trim();
                            cddjl.CDRQ = TxtCurrtDate.CurrentTime;
                            var result = LYCDDal.Add_CDDJL(cddjl);
                            if (result.Code == ResultCode.Success)
                                MessShow.ShowSure("存档日期：" + TxtCurrtDate.CurrentTime.ToString("yyyy-MM-dd") + ",已同步存档");
                            else if (result.Code == ResultCode.Fail)
                                MessShow.ShowHint(result.Message);
                            else
                                MessShow.ShowMistake(result.Message);
                        }
                    });
                }, null, this);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 公告提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucBtnExt1_BtnClick(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TxtGGNR.Text))
            {
                MessShow.ShowHint("请输入公告内容后再提交");
                return;
            }

            QH_GGTX ggtx = new QH_GGTX();
            ggtx.ID = CommonHelper.GetNewGuid();
            ggtx.GGLX = TxtGGLX.SelectedValue.Trim();
            ggtx.GGNR = TxtGGNR.Text;
            ggtx.FBZH = CookieData.getInstance().YHXX.DLZH;
            var result = LYCDDal.Add_GGTX(ggtx);
            if (result.Code == ResultCode.Success)
                MessShow.ShowSure(TxtGGLX.SelectedText + "发布成功，请重启工具");
            else if (result.Code == ResultCode.Fail)
                MessShow.ShowHint(result.Message);
            else
                MessShow.ShowMistake(result.Message);
        }
    }
}
